//
//  YSFlowAdjustCompileViewController.m
//  YaSha-iOS
//
//  Created by YaSha_Tom on 2018/10/19.
//  Copyright © 2018年 亚厦装饰股份有限公司. All rights reserved.
//

#import "YSFlowAdjustCompileViewController.h"
#import "YSNewsAttachmentModel.h"

@interface YSFlowAdjustCompileViewController ()
@property (nonatomic, strong) NSMutableArray *basicInformationArr;
@end

@implementation YSFlowAdjustCompileViewController
#pragma mark -- 懒加载
- (NSMutableArray *)basicInformationArr {
    if (!_basicInformationArr) {
        _basicInformationArr = [NSMutableArray array];
    }
    return _basicInformationArr;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self doNetworking];
}
- (void)doNetworking {
    NSString *urlString = [NSString stringWithFormat:@"%@%@/%@/%@",YSDomain,getAdjustOriginalByIdApi,self.cellModel.businessKey,self.cellModel.processInstanceId];
    [QMUITips showLoadingInView:self.view];
    DLog(@"========%@",urlString);
    [YSNetManager ys_request_GETWithUrlString:urlString isNeedCache:NO parameters:nil successBlock:^(id response) {
        DLog(@"编制调整申请详情:%@",response);
        [QMUITips hideAllTipsInView:self.view];
        if ([response[@"code"] intValue] == 1) {
            self.flowFormModel = [YSFlowFormModel yy_modelWithJSON:response[@"data"]];
            self.coverNavView.titleLabel.text = self.flowFormModel.baseInfo.title;
            [self.functionHeaderView setHeaderModel:self.flowFormModel.baseInfo];
            [self setUpData:self.flowFormModel.info];
            if ([self.flowFormModel.info[@"adjustOriginalFiles"] count] > 0) {
                for (NSDictionary *dic in self.flowFormModel.info[@"adjustOriginalFiles"]) {
                    YSNewsAttachmentModel *model = [YSNewsAttachmentModel yy_modelWithJSON:dic];
                    [self.attachArray addObject:model];
                }
            }
            if (self.attachArray.count > 0) {
                [self.functionHeaderView.documentButton setTitle:[NSString stringWithFormat:@"关联文档(%lu)",(unsigned long)self.attachArray.count] forState:UIControlStateNormal];
            }
            [self.postscriptArray addObject:@{@"title":@" ",@"content":self.flowFormModel.info[@"postscript"],@"special":@"4"}];
            [self.tableView reloadData];
            //定位当前的标题位置（该计算要在tableView刷新之后计算来保证header位置的准确）
            dispatch_async(dispatch_get_main_queue(), ^{
                [self markSectionHeaderLocation];
            });
        }
    } failureBlock:^(NSError *error) {
        
    } progress:nil];
    
    //审批记录
    NSString *urlStringRecord = [NSString stringWithFormat:@"%@%@/%@/1", YSDomain, getCommentsByProcessInstanceIdApi, self.cellModel.processInstanceId];
    DLog(@"=========%@",urlString);
    [YSNetManager ys_request_GETWithUrlString:urlStringRecord isNeedCache:NO parameters:nil successBlock:^(id response) {
        DLog(@"处理列表:%@", response);
        self.recordArray = [[YSDataManager getFlowRecordListData:response] mutableCopy];
        [self.tableView reloadData];
        //定位当前的标题位置（该计算要在tableView刷新之后计算来保证header位置的准确）
        dispatch_async(dispatch_get_main_queue(), ^{
            [self markSectionHeaderLocation];
        });
        
    } failureBlock:^(NSError *error) {
        
    } progress:nil];
    
    //转阅记录列表
    NSString *urlStringTurn = [NSString stringWithFormat:@"%@%@/%@/2", YSDomain, getCommentsByProcessInstanceIdApi, self.cellModel.processInstanceId];
    DLog(@"=========%@",urlString);
    [YSNetManager ys_request_GETWithUrlString:urlStringTurn isNeedCache:NO parameters:nil successBlock:^(id response) {
        DLog(@"处理列表:%@", response);
        self.turnArray = [[YSDataManager getFlowRecordListData:response] mutableCopy];
        [self.tableView reloadData];
        //定位当前的标题位置（该计算要在tableView刷新之后计算来保证header位置的准确）
        dispatch_async(dispatch_get_main_queue(), ^{
            [self markSectionHeaderLocation];
        });
    } failureBlock:^(NSError *error) {
        
    } progress:nil];
}
#pragma mark -- 数据封装
- (void)setUpData:(NSDictionary *)dic {
    [self.basicInformationArr addObject:@{@"title":@"编制信息",@"content":@" ",@"special":@"1"}];
    [self.basicInformationArr addObject:@{@"title":@"编制部门",@"content":dic[@"deptName"],@"special":@"0"}];
    [self.basicInformationArr addObject:@{@"title":@"编制类型",@"content":dic[@"originalType"],@"special":@"0"}];
    [self.basicInformationArr addObject:@{@"title":@"编制详情",@"content":@" ",@"special":@"1"}];
    for (NSDictionary *dic1 in dic[@"adjustOriginalPositions"]) {
        for (NSDictionary *dic2 in dic1[@"adjustOriginalPositionRanks"]) {
            [self.basicInformationArr addObject:@{@"title":[NSString stringWithFormat:@"%@序列-%@",dic2[@"rankCode"],dic1[@"positionName"]],@"content":@" ",@"special":@"5"}];
            [self.basicInformationArr addObject:@{@"title":@"原有编制",@"content":[NSString stringWithFormat:@"%@人",dic2[@"rankNumOld"]],@"special":@"0"}];
            [self.basicInformationArr addObject:@{@"title":@"调整编制",@"content":[NSString stringWithFormat:@"%@人",dic2[@"rankSum"]],@"special":@"0"}];
            [self.basicInformationArr addObject:@{@"title":@"调整过后编制",@"content":[NSString stringWithFormat:@"%@人",dic2[@"rankNum"]],@"special":@"0"}];
        }
    }
    [self.basicInformationArr addObject:@{@"title":@"备注",@"content":@" ",@"special":@"1"}];
    [self.basicInformationArr addObject:@{@"title":@"备注",@"content":dic[@"remarks"],@"special":@"0"}];
    self.dataSourceArray = self.basicInformationArr;
    
}
//在数据加载完后，从新设置定位位置
-(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    [self markSectionHeaderLocation];
} 
# pragma mark -- tableView deletage
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(indexPath.section == 0){
        NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%ld%ld", (long)indexPath.section,(long)indexPath.row];//以indexPath来唯一确定cell
        YSFlowFormListCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; //出列可重用的cell
        
        if (cell == nil) {
            cell = [[YSFlowFormListCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }
        [cell setNewFlowDetailWithDictionary:self.dataSourceArray[indexPath.row]];
        return cell;
    }else if (indexPath.section == 1) {
        YSFlowFormListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"]; //出列可重用的cell
        if (cell == nil) {
            cell = [[YSFlowFormListCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        }
        [cell setNewFlowDetailWithDictionary:self.postscriptArray[indexPath.row]];
        return cell;
    }else if(indexPath.section == 2){
        YSFlowRecordListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellExaminationList]; //出列可重用的cell
        if (cell == nil) {
            cell = [[YSFlowRecordListCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellExaminationList];
        }
        if (self.recordArray.count > 0) {
            YSFlowRecordListModel *cellModel = self.recordArray[indexPath.row];
            [cell setRecordListCellModel:cellModel andIndexPath:indexPath];
            [self callPhone:cellModel.userId andTableViewCell:cell];
        }
        return cell;
    }else{
        YSFlowRecordListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifierFlow]; //出列可重用的cell
        if (cell == nil) {
            cell = [[YSFlowRecordListCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifierFlow];
        }
        if (self.turnArray.count > 0) {
            YSFlowRecordListModel *cellModel = self.turnArray[indexPath.row];
            [cell setRecordListCellModel:cellModel andIndexPath:indexPath];
            [self callPhone:cellModel.userId andTableViewCell:cell];
        }
        return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath  {
    if (indexPath.section == 0) {
        NSDictionary *dic = self.dataSourceArray[indexPath.row];
        if ([dic[@"special"] isEqualToString:@"3"]) {
            YSFlowFormListCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
            //           cell.button.selected = !cell.button.selected;
            if (cell.button.selected) {
                cell.button.selected = NO;
                [self.dataSourceArray removeObjectAtIndex:indexPath.row+1];
                [self.tableView beginUpdates];
                NSIndexPath *indexPathDelete = [NSIndexPath indexPathForRow:indexPath.row+1 inSection:0];
                [self.tableView deleteRowsAtIndexPaths:@[indexPathDelete] withRowAnimation:UITableViewRowAnimationAutomatic];
                [self.tableView endUpdates];
                self.selectMenu.alpha = 1;
                self.coverNavView.alpha = 1;
                
            }else{
                cell.button.selected = YES;
                [self.dataSourceArray insertObject:@{@"title":@"",@"content":dic[@"content"],@"special":@"4"} atIndex:indexPath.row+1];
                [self.tableView beginUpdates];
                NSIndexPath *indexPathAdd = [NSIndexPath indexPathForRow:indexPath.row+1 inSection:0];
                [self.tableView insertRowsAtIndexPaths:@[indexPathAdd] withRowAnimation:UITableViewRowAnimationAutomatic];
                [self.tableView endUpdates];
                self.selectMenu.alpha = 1;
                self.coverNavView.alpha = 1;
            }
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
